package cm.tl.pms.webservice;

import cm.tl.pms.common.entity.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
import org.springframework.cache.interceptor.CacheResolver;

import java.util.Collection;
import java.util.Collections;

public class CustomCacheResolver implements CacheResolver {

    @Autowired
    private CacheManager cacheManager;

    @Override
    public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {
        String cacheName = context.getOperation().getCacheNames().iterator().next();
        Cache cache = cacheManager.getCache(cacheName);
        Object cachedValue = cache.get(context.getTarget());
        if (cachedValue instanceof ResultMsg) {
            ResultMsg resultMsg = (ResultMsg) cachedValue;
            if (resultMsg != null && resultMsg.getData() == null) {
                return null;
            }
        }

        return Collections.singletonList(cache);
    }
}